#include "Buzzercommander.h"

BuzzerCommander::BuzzerCommander(SerialPort *sp, QWidget *parent) :
		QMainWindow(parent) {
	ui.setupUi(this);
	this->sp = sp;

	QObject::connect(sp, SIGNAL(portOpened()), this, SLOT(portOn()));
	QObject::connect(sp, SIGNAL(portClosed()), this, SLOT(portOff()));
	QObject::connect(sp, SIGNAL(dataReady()), this, SLOT(dataListener()));

	QObject::connect(ui.actionDebug_Modus, SIGNAL(toggled(bool)), this, SLOT(toggleSize()));

	portOpen = false;

	// hide Debug Widget
	ui.groupBoxDebug->setVisible(true);
	this->toggleSize();
}

BuzzerCommander::~BuzzerCommander() {

}

void BuzzerCommander::on_actionOpen_triggered(bool checked) {
	sp->show();
}

void BuzzerCommander::on_actionClose_triggered(bool checked) {
	sp->closePort();
}

void BuzzerCommander::on_actionExit_triggered(bool checked) {
	this->close();
}

void BuzzerCommander::on_btnSend_clicked() {

	// convert hex text to int representation
	// "ff" becomes 255
	bool ok;
	unsigned int num = ui.input->text().toUInt(&ok, 16);
	if (ok) {
		qDebug() << num;
		qDebug() << QString::number(num, 16);
	}

	// store int in byte array
	QByteArray bytes = QByteArray::number(num, 16).toUpper();

	// send it to serial port
	sp->send(bytes.size(), bytes.data());

	if (portOpen) {
		ui.serialLog->append("<font color=blue>" + QString(bytes.data()) + "</font>");
	} else {
		ui.serialLog->append("<font color=red>" + QString(bytes.data()) + "</font>");
	}
	ui.input->setValue(0);
}

void BuzzerCommander::portOn() {
	this->statusBar()->showMessage("Port open");
	portOpen = true;
}

void BuzzerCommander::portOff() {
	this->statusBar()->showMessage("Port closed");
	portOpen = false;
}

void BuzzerCommander::dataListener() {
	char buffer[256];
	int rec = sp->receive(255, buffer);
	buffer[rec] = '\0';
	ui.serialLog->append(buffer);
}

void BuzzerCommander::toggleSize(){
	ui.centralwidget->setFixedSize(ui.centralwidget->sizeHint());
	this->adjustSize();
}
